<?php
/**
 * Smart Library - Smart Framework
 * http://smart-framework.highet.eu
 *
 * @category   SmartL
 * @package    SmartL_Zend
 * @subpackage Validate
 * @copyright  Copyright (c) 2005-2008 Smart Framework team - Stepan Sindelar, Vojtech Vit
 * @license    http://www.opensource.org/licenses/bsd-license.php	New BSD License
 */

/**
 * @see Zend_Validate_Abstract
 */
require_once ('Zend/Validate/Abstract.php');

/**
 * Validator for common scenario when you need to check if password or other credential element matches.
 * You must set list of credentials that are compared with user input.
 * This validator is not implemented in Zend framework.
 * <?php
 * 	$validator = new SmartL_Zend_Validate_ConfirmCredential();
 * 	$validator->setCredentials(array('the-password-check'));
 * 	$form->myPwElement->addValidator($validator);
 * ?>
 * 
 * @package SmartL_Zend
 * @subpackage Validate
 */
class SmartL_Zend_Validate_ConfirmCredential extends Zend_Validate_Abstract {
	/**
	 * Containt for id of error message.
	 *
	 */
	const NOT_MATCH = 'notMatch';
	/**
	 * Credentials for validation of element.
	 *
	 * @var string
	 */
	private $_credentials = array ();
	/**
	 * Array of error messages.
	 *
	 * @var array
	 */
	protected $_messageTemplates = array (self::NOT_MATCH => 'Password confirmation does not match the original password.' );
	
	public function __construct(array $credentials = array()) {
		$this->setCredentials ( $credentials );
	}
	
	/**
	 * Adds credential for validation of element.
	 * @param string $credential
	 */
	public function addCredential($value) {
		$this->_credentials [] = $value;
	}
	
	/**
	 * Sets array of credentials for validation.
	 * @param array[numeric]=>string $credentials
	 */
	public function setCredentials(array $credentials) {
		$this->_credentials = $credentials;
	}
	
	/**
	 * Process validation and return results.
	 * It is implemetation of method from Zend_Validate_Abstract.
	 *
	 * @param string $value Value of checked field.
	 * @param array $context Values of other fields in form.
	 * @return boolean
	 */
	public function isValid($value, $context = null) {
		$value = ( string ) $value;
		$this->_setValue ( $value );
		foreach ( $this->_credentials as $credential ) {
			if (! isset ( $context [$credential] )) {
				require_once 'SmartL/Zend/Validate/Unique/Exception.php';
				throw new SmartL_Zend_Validate_Unique_Exception ( "Password confirmation field {$credential} wasn't found in context" );
			}
			if ($context [$credential] !== $value) {
				$this->_error ( self::NOT_MATCH );
				return false;
			}
		}
		return true;
	}
}
